package com.yancloud.android.manager;

import android.util.Log;

import com.koushikdutta.async.http.server.AsyncHttpServer;
import com.koushikdutta.async.http.server.AsyncHttpServerRequest;
import com.koushikdutta.async.http.server.AsyncHttpServerResponse;
import com.koushikdutta.async.http.server.HttpServerRequestCallback;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Created by root on 7/25/17.
 */

public class URICallback implements HttpServerRequestCallback {
    String url;
    Method m;
    public static ExecutorService executor = Executors.newFixedThreadPool(5);
    public URICallback(String url, Method m){
        this.url = url;
        this.m = m;
    }
    @Override
    public void onRequest(final AsyncHttpServerRequest request, final AsyncHttpServerResponse response) {
        Log.d("URICallback",url+" req:"+request.toString());
            executor.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        m.invoke(null,request,response);
                    } catch (Throwable e) {
                        ByteArrayOutputStream bo= new ByteArrayOutputStream();
                        e.printStackTrace(new PrintStream(bo));
                        response.send(bo.
                                toString());
                        e.printStackTrace();
                    }
                }
            });
    }
    public void register(AsyncHttpServer server){
        server.get(url,this);
    }
}